package com.youhome.service.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.youhome.common.config.OSSConfig;
import com.youhome.service.mapper.ListHubMapper;
import com.youhome.service.model.HouseBasicInfo;
import com.youhome.service.model.ListHub;
import com.youhome.service.service.HouseService;
import com.youhome.service.service.OSSService;
import com.youhome.utils.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by chen365 on 2018/05/17.
 */
@Service
public class HouseServiceImpl implements HouseService {

    @Autowired
    private OSSConfig ossConfig;
    @Autowired
    private ListHubMapper listHubMapper;
    @Autowired
    private OSSService ossService;

    @Override
    public HouseBasicInfo selectHouseBasicInfo(String houseId) {

        ListHub listHub = listHubMapper.selectByPrimaryKey(houseId);
        HouseBasicInfo houseBasicInfo = new HouseBasicInfo();

        if (listHub != null && !StringUtils.isEmpty(listHub.getListingKey())) {
            String key = "json/" + listHub.getListingKey() + ".json";
            try {
                OSSClient ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
                String json = ossService.downloadJson(ossClient, ossConfig.getBacketName(), key);
                if (!StringUtils.isEmpty(json)) {
                    JSONObject dataJson = JSON.parseObject(json);
                    if (dataJson.get("listingDescription") != null && !dataJson.get("listingDescription").equals("null")) {
                        String listingDescription = (String) dataJson.get("listingDescription");
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                return null;
            }
        }
        return houseBasicInfo;
    }

    @Override
    public boolean selectExistsByPrimaryKey(String houseId) {
        if (listHubMapper.selectExistsByPrimaryKey(houseId) > 0) {
            return true;
        }
        return false;
    }
}
